package com.amkor.study.ldap.rpc;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class LdapTest {
	private static String LDAP_INIT_CTX_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
	private static String LDAP_DOMAIN = "LDAP://chazlds02.amkor.com:389/";
	
	public static void main(String[] args) {
		
		
		boolean isAuthenticated = false;
		DirContext ctx = null;
		
		try{
		
			String userId = "";
			String passwd = "";
			
			ctx = new InitialDirContext(getProperties(userId, passwd));			
			isAuthenticated = true;
			
		/* comment if you do not want ldap information */ 		 
		  SearchControls sc = new SearchControls(SearchControls.SUBTREE_SCOPE, 0, 6000, null, true, true);
		  NamingEnumeration<SearchResult> results = ctx.search("o=aaww", "(uid="+userId+")", sc);
		  if(results != null){
		    while(results.hasMore()){
					SearchResult result = results.next();
					Attributes attrs = result.getAttributes();
				// get each attribute that you want. 	
System.out.println("displayName =======>"+attrs.get("displayName"));
System.out.println("department =======>"+attrs.get("department"));
				}
		  }
		  
		/* fill out how to send result to cliet side. */	
				
		}catch(NamingException ne){
		/* fill out how to handle "NamingException" */
			
			ne.printStackTrace();
		}
		
	}
	
	private static Hashtable<String, String> getProperties(String userId, String passwd){
		Hashtable<String, String> props = new Hashtable<String, String>();		
		props.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_INIT_CTX_FACTORY);
		props.put(Context.PROVIDER_URL, LDAP_DOMAIN);
		props.put(Context.SECURITY_AUTHENTICATION, "simple");
		props.put(Context.SECURITY_PRINCIPAL, userId);
		props.put(Context.SECURITY_CREDENTIALS, passwd);	
		return props;
	}
	
}
